// Copyright (C) 1995 Steve Hayman
// Use is governed by the MiscKit license

#import "MiscAwakeAction.h"
#import <apps/InterfaceBuilder.h>
#define AWAKE_ACTION_VERSION 0

@implementation MiscAwakeAction

/*
 * The meat of the class.  Send a message somewhere.
 */
 
- fire
{
    if ( _target && action && [_target respondsTo:action] ) {
	[_target perform:action with:self];
    }    
    return self;
}

/*
 * We get "awakeFromNib" when our nib file is loaded by a running
 * application, after all the outlets are set up.
 * Good time to fire the target/action.
 */
- awakeFromNib
{
    return [self fire];
}

/*
 * Bug in 3.1 and later: [NXApp isTestingInterface] always yields
 * NO during read/write/awake.  Use this workaround.  See NeXTanswers
 * #1525.  This idea is from FilenameList.m in the StringList miniexample
 */
- awake
{
    // test to see if mainMenu is visible, which it isn't while test
    // interface mode is being set up. 
    
    if([NXApp conformsTo:@protocol(IB)]) {
	if(! [[NXApp mainMenu] isVisible]) {
	    // main menu not visible, must be entering test mode
	    // (although this also happens when we are loading a .nib
	    //  at IB startup time, i.e. if you doubleclick on a .nib
	    //  and ib is opening it while starting up. no big deal.

	    return [self perform:@selector(fire) with:nil 
		afterDelay:1 cancelPrevious:YES];
	}
    }
    return nil;
}

- target
{
    return _target;
}
- setTarget:t
{
    _target = t;
    return self;
}
- (SEL)action
{
    return action;
}
- setAction:(SEL)a
{
    action = a;
    return self;
}

- read:(NXTypedStream *)stream
{
    int version;

    [super read:stream];
    version = NXTypedStreamClassVersion(stream, "MiscAwakeAction");
    switch (version) {
    case AWAKE_ACTION_VERSION:
	NXReadTypes(stream, "@:", &_target, &action);
	
	if ( [NXApp respondsTo:@selector(isTestingInterface)]
	    && [NXApp isTestingInterface] ) {
	

	    [self perform:@selector(fire) with:nil afterDelay:1 
		cancelPrevious:YES];
	}

	break;
    default:
	NXLogError("[%s %s] - unknown version of %s in typed stream",
		[[self class] name], sel_getName(_cmd), 
		[[self class] name]);
	break;
    }
    return self;
}

- write:(NXTypedStream *)stream
{
    [super write:stream];
    
	NXWriteTypes(stream, "@:", &_target, &action);
    
    return self;
}


@end

